<!DOCTYPE html>
<html lang="en">
<head>
    @@include('../_include/head.html',{
    "title":"考试系统后台管理",
    "filePath":"../.."
    })
    <link rel="stylesheet" href="../../css/examine.css">
    <link rel="stylesheet" href="../../lib/layui/css/layui.css">
    <link rel="stylesheet" href="../../css/common.css">
    <style type="text/css">
        .options-list li {
            height: 28px;
            margin-bottom: 5px;
        }

        .options-list li .title {
            display: inline-block;
            width: 30px;
        }

        .options-list li .layui-input {
            width: calc(100% - 35px);
            display: inline-block;
        }
    </style>
</head>
<body class="iframe" style="height: calc(100% - 10px)">
<div class="layui-main x-frame2 layui-collapse" lay-filter="collapsePanel" style="margin-top: 10px;">
    <div class="layui-colla-item colla-off">
        <div class="layui-colla-title">试题列表
            <span class="layui-colla-subtitle"></span>
            <span class="layui-colla-toolbar">
                <button class="layui-btn layui-btn-normal" onclick="app.openPop('add')"><i
                        class="layui-icon layui-icon-add-1"></i>添加试题</button>
                <button class="layui-btn layui-btn-normal" onclick="app.batchRemove()"><i
                        class="layui-icon layui-icon-delete"></i>批量删除</button>
            </span>
        </div>
        <div class="layui-colla-content layui-show layui-colla-content-footer">
            <table id="myTable" lay-filter="myTable"></table>
        </div>
    </div>
</div>
<!-- 弹窗操作 -->
<div id="popLayer" class="popform" style="display: none;">
    <form class="layui-form" id="chiocePop" lay-filter="choiceForm">
        <div class="layui-form-item">
            <label class="layui-form-label form-required">试题类型</label>
            <div class="layui-input-inline">
                <select name="timulx" lay-filter="timulx" required lay-verify="isChoiceRequired">
                    <option value="1">单选题</option>
                    <option value="2">选择题</option>
                    <option value="3">判断题</option>
                </select>
            </div>
        </div>
        <div id="popchicoe">
            <div class="layui-form-item">
                <label class="layui-form-label form-required">正确答案</label>
                <div class="layui-input-inline">
                    <input type="text" name="timudaan" required lay-verify="isChoiceRequired" placeholder="ABCD"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label form-required">试题题目</label>
                <div class="layui-input-block">
                    <textarea name="timu" placeholder="请输入内容" required lay-verify="isChoiceRequired"
                              style="min-height: 100px;"
                              class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label form-required">试题选项</label>
                <div class="layui-input-block">
                    <ul class="options-list" id="optionsList"></ul>
                    <input class="layui-btn layui-btn-primary addbtn" type="button" value="新增选项" id="addOption">
                </div>
            </div>
        </div>
        <div id="popjudge" style="display: none;">
            <div class="layui-form-item">
                <label class="layui-form-label form-required">正确答案</label>
                <div class="layui-input-inline">
                    <select name="judgeAnswer" required lay-verify="isJudgeRequired">
                        <option value="Y">是</option>
                        <option value="N">否</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label form-required">试题题目</label>
                <div class="layui-input-block">
                    <textarea name="judgeTitle" placeholder="请输入内容" required lay-verify="isJudgeRequired"
                              style="min-height: 100px;" class="layui-textarea"></textarea>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitExamination">立即提交</button>
            </div>
        </div>
    </form>
</div>

@@include('../_include/js.html',{
"filePath":"../.."
})
<script type="text/html" id="approvalStatus">
    {{#
    var statusMap={
    1: {class: "tip-bg1", text: "单选题"},
    2: {class: "tip-bg2", text: "多选题" },
    3: {class: "tip-bg3", text: "判断题" }
    }
    }}
    <span class="tip status {{=statusMap[d.timulx].class}}">{{=statusMap[d.timulx].text}}</span>

</script>
<script type="text/html" id="operateCol">
    <a class="x-operate-btn" lay-event="edit">
        <i class="layui-icon">&#xe642;</i>编辑</a>
    <a class="x-operate-btn" lay-event="delete">
        <i class="layui-icon">&#xe640;</i>删除</a>
</script>
<script type="text/html" id="newOptions">
    {{#  layui.each(d, function(index, item){ }}
    <li>
        <span class="title">{{item.type}}：</span>
        <input type="text" value="{{item.value}}" name="{{'type_'+item.type}}" required lay-verify="isChoiceRequired"
               placeholder="请输入选项内容"
               autocomplete="off" class="layui-input">
    </li>
    {{#  }); }}
    {{#  if(d.length === 0){ }}
    无数据
    {{#  } }}
</script>
<script>
    var tableHead = [
        {type: 'checkbox'},
        {field: 'shiTiId', hide: true},
        {field: 'timulx', width: 100, title: '试题类型', align: 'center', templet: '#approvalStatus', unresize: true},
        {field: 'timu', title: '试题题目', align: 'center'},
        {field: 'timudaan', width: 80, title: '答案', align: 'center'},
        {field: 'cjsj', width: 180, title: '添加时间', align: 'center', templet: function (d) {
                return new Date(d.cjsj).toLocaleDateString()
            }},
        {field: 'operate', width: 145, title: '操作', align: 'center', toolbar: '#operateCol'},
    ]

    var app = {
        Table: layui.table,
        Layer: layui.layer,
        Form: layui.form,
        Event: layui.event,
        Laytpl: layui.laytpl,
        popupLayer: null,
        editId: null,
        baseOptions: [],
        optionsIndex: 0,
        init() {
            this.renderTable()
            this.bindEvents()
        },
        /**
         * 事件绑定
         */
        bindEvents() {
            var _self = this;

            this.Form.verify({
                isJudgeRequired: function (value) { //value：表单的值、item：表单的DOM对象
                    if ($("#popjudge").is(":visible")) {
                        if (value.length === 0) {
                            return '必填项不能为空';
                        }
                    }
                },
                isChoiceRequired: function (value) { //value：表单的值、item：表单的DOM对象
                    if ($("#popchicoe").is(":visible")) {
                        if (value.length === 0) {
                            return '必填项不能为空';
                        }
                    }
                }
            });
            this.Form.on('select(timulx)', function (data) {
                if (parseInt(data.value) !== 3) {
                    $("#popjudge").hide()
                    $("#popchicoe").show()
                } else {
                    $("#popchicoe").hide()
                    $("#popjudge").show()
                }
            })

            this.Form.on('submit(submitExamination)', function (data) {
                if (data.field) {
                    // 添加/编辑，保存内容
                    _self.submitForm(data.field)
                } else {
                    return null;
                }
            })

            this.Table.on('tool(myTable)', function (obj) {
                var data = obj.data, layEvent = obj.event;
                switch (layEvent) {
                    case 'edit':
                        _self.openPop('edit', data);
                        break;
                    case 'delete':
                        _self.remove(data);
                        break;
                }
            });

            $('#addOption').click(function () {
                _self.addOption()
            })
        },
        /**
         * 渲染表格
         */
        renderTable() {
            this.Table.render({
                id: 'myTable',
                elem: '#myTable',
                url: API_HOST + '/zczhf/api/examGL/getList', // 异步操作数据接口
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                headers: {
                    authorization: localStorage.getItem('authorization')
                },
                method: 'POST',
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                contentType: 'application/json',
                limit: 10,
                page: { //开启分页
                    theme: 'table',
                    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
                    prev: '上一页',
                    next: '下一页'
                },
                height: 'full-100',
                cols: [tableHead]
            });
        },
        /**
         * 打开新增、编辑的弹窗
         */
        openPop(type, data) {
            var title = '编辑';
            this.baseOptions = []
            if (type === 'add') {
                this.editId = null;
                title = '添加'
                var i = 0;
                for (i; i < 4; i++) {
                    this.baseOptions.push({type: String.fromCharCode(65 + i), value: ''})
                }
                this.optionsIndex = i

                this.Form.val("choiceForm", {
                    timulx: 1,
                    timudaan: '',
                    timu: '',
                    judgeAnswer: 'Y',
                    judgeTitle: ''
                })
            } else {
                this.editId = data.shiTiId;
                if (parseInt(data.timulx) !== 3 && data.optisons) {
                    var options = JSON.parse(data.optisons)
                    for (var key in options) {
                        this.baseOptions.push({type: key, value: options[key]})
                    }
                }

                this.Form.val("choiceForm", {
                    timulx: data.timulx,
                    timu: parseInt(data.timulx) === 3 ? '' : data.timu,
                    timudaan: parseInt(data.timulx) === 3 ? '' : data.timudaan,
                    judgeTitle: parseInt(data.timulx) === 3 ? data.timu : '',
                    judgeAnswer: parseInt(data.timulx) === 3 ? data.timudaan : ''
                })

                if (parseInt(data.timulx) !== 3) {
                    $("#popjudge").hide()
                    $("#popchicoe").show()
                } else {
                    $("#popchicoe").hide()
                    $("#popjudge").show()
                }

                this.Form.render('select', 'choiceForm')
                this.optionsIndex = this.baseOptions.length
            }
            this.popupLayer = this.Layer.open({
                type: 1,
                title: title + "试题",
                area: ['70%', '90%'],
                content: $("#popLayer")
            })
            this.renderOptions(this.baseOptions)
        },
        /**
         * 渲染选项
         */
        renderOptions(options) {
            var template = newOptions.innerHTML;
            this.Laytpl(template).render(options, function (html) {
                optionsList.innerHTML = html;
            });
        },
        /**
         * 新增一行选项
         */
        addOption() {
            this.baseOptions = []
            var currIndex = ++this.optionsIndex
            for (var i = 0; i < currIndex; i++) {
                var type = String.fromCharCode(65 + i);
                this.baseOptions.push({type: type, value: $('input[name=type_' + type + ']').val() || ''})
            }
            this.renderOptions(this.baseOptions)
        },
        /**
         * 提交增加、编辑的表单
         */
        submitForm(form) {
            var _self = this, url, options = [], data = {
                timulx: form.timulx,
                timu: null,
                timudaan: null,
                optisons: null,
            };

            if (parseInt(form.timulx) !== 3) {
                // 单选题、多选题
                data.timu = form.timu
                data.timudaan = form.timudaan
                var currIndex = this.optionsIndex
                for (var i = 0; i < currIndex; i++) {
                    var type = String.fromCharCode(65 + i)
                    options.push(form['type_' + type])
                }
                data.optisons = options.join('#&#')
            } else {
                // 判断题
                data.timu = form.judgeTitle
                data.timudaan = form.judgeAnswer
            }

            if (this.editId) {
                data.shiTiId = this.editId
                url = '/zczhf/api/examGL/update'
            } else {
                url = '/zczhf/api/examGL/add'
            }

            _fn.requestData(url, data, {
                success: function (data) {
                    if (data.code === 0) {
                        _self.showMessage('保存成功！', function () {
                            _self.reload();
                            _self.Layer.closeAll()
                        })
                    } else {
                        _self.showMessage(data.msg)
                    }
                }
            })

            return false;
        },
        /**
         * 删除单条试题
         */
        remove(data) {
            var _self = this;
            this.Layer.confirm('是否删除此试题？', function (index) {
                _fn.requestData('/zczhf/api/examGL/delete', {shiTiId: data.shiTiId}, {
                    success: function (data) {
                        if (data.code === 0) {
                            _self.showMessage('删除成功！', function () {
                                _self.reload();
                                _self.Layer.closeAll()
                            })
                        } else {
                            _self.showMessage(data.msg)
                        }
                    }
                }, 'GET')
            });
        },
        /**
         * 批量删除试题
         */
        batchRemove() {
            var data = this.Table.checkStatus('myTable').data, _self = this;
            if (!data.length) {
                this.showMessage('请至少选择一条数据进行删除！')
                return false;
            }

            var id = []
            for (var i = 0; i < data.length; i++) {
                id.push(data[i].shiTiId)
            }
            // 批量删除的接口
            this.Layer.confirm('是否删除选中的试题？', function (index) {
                _fn.requestData('/zczhf/api/examGL/delete', {shiTiId: id.join('_')}, {
                    success: function (data) {
                        if (data.code === 0) {
                            _self.showMessage('删除成功！', function () {
                                _self.reload();
                                _self.Layer.closeAll()
                            })
                        } else {
                            _self.showMessage(data.msg)
                        }
                    }
                }, 'GET')
            });
        },
        /**
         * 显示成功、失败信息
         * @param msg
         * @param callback
         */
        showMessage(msg, callback) {
            this.Layer.msg(msg, {time: 1000}, callback && callback());
        },
        /**
         * 重载表格
         */
        reload() {
            this.Table.reload('myTable')
        }
    }

    app.init();
</script>
</body>
</html>